// Copyright (c) 2022 Presto Labs Pte. Ltd.
// Author: juntang

#include "coin2/exchange/bitget/api_order/native_private_client.h"

#include <list>
#include <memory>
#include <sstream>
#include <string>

#include "coin2/exchange/base/api_util/url_params_builder.h"
#include "coin2/exchange/bitget/symbology/product.h"

using coin2::exchange::bitget::symbology::BitgetProduct;
using AsioHttpContextList = std::list<std::shared_ptr<AsioHttpContext>>;

#define CHECK_API_LIMIT(action_type, query_type)                                               \
  if (local_rate_tracker_ &&                                                                   \
      (!local_rate_tracker_->HasEnoughRateLimit(ts, action_type, query_type))) {               \
    LOG_EVERY_N(WARNING, 50) << "Hit rate limit or api temporary disabled until " << __func__; \
    api_block_info_[__func__]++;                                                               \
    return {};                                                                                 \
  }

namespace {
using ActionType = bitget::api_util::BitgetRateTracker::ActionType;
using coin2::exchange::bitget::api_util::BitgetRateTracker;
using QueryType = coin2::exchange::bitget::api_util::QueryType;
}  // namespace

namespace coin2::exchange::bitget::api_order {

auto BitgetNativePrivateClient::GetRestOrderParams(
    const OrderSpec& order_spec,
    int64_t proc_order_id,
    int64_t orig_proc_order_id) -> RestParams {
  auto params = RestParams();

  BitgetProduct product = BitgetProduct::FromStr(order_spec.product, order_spec.order_created_time);
  auto product_holder = GetProductHolder(product, order_spec.order_created_time);
  params.set_symbol(order_spec.product);
  auto formatter = product_holder->product_info().order_formatter();
  if (order_spec.order_type != OrderType::MARKET_ORDER) {
    params.set_price(formatter.FormatPrice(order_spec.price));
  }
  params.set_quantity(formatter.FormatQty(order_spec.qty));
  params.set_client_order_id(std::to_string(proc_order_id));

  if (orig_proc_order_id > 0) {
    params.set_order_id(std::to_string(orig_proc_order_id));
  }

  if (order_spec.order_type == OrderType::MARKET_ORDER) {
    params.set_order_type("market");
  } else {
    params.set_order_type("limit");
  }

  if (order_spec.post_only) {
    params.set_force("post_only");
  } else if (order_spec.duration == coin::proto::OrderDuration::FOK_ORDER) {
    params.set_force("fok");
  } else if (order_spec.duration == coin::proto::OrderDuration::IOC_ORDER) {
    params.set_force("ioc");
  } else {
    params.set_force("normal");
  }

  if (order_spec.order_side == OrderSide::BUY_ORDER) {
    params.set_side("buy");
  } else if (order_spec.order_side == OrderSide::SELL_ORDER) {
    params.set_side("sell");
  } else {
    NOTREACHED() << "Unknown order side: " << static_cast<int>(order_spec.order_side);
  }

  return params;
}

auto BitgetNativePrivateClient::GetRestCancelParams(const IOrderContext& order_context)
    -> RestParams {
  auto params = RestParams();
  const std::string& product_str = order_context.order_spec().product;
  params.set_symbol(product_str);
  if (order_context.has_exchange_order_id()) {
    params.set_order_id(order_context.exchange_order_id());
  } else {
    params.set_order_id(std::to_string(order_context.proc_order_id()));
  }
  return params;
}

BitgetNativePrivateClient::BitgetNativePrivateClient(
    const MarketExchangeApi& mea,
    const NativeClientConfig& config_override) {
  mea_ = mea;
  using coin2::exchange::bitget::api_util::BitgetRateTracker;
  NativeClientConfig config;
  config.set_rest_host("api.bitget.com");
  config.set_rest_host_port(443);
  config.MergeFrom(config_override);

  auths_.Construct<BitgetRestAuth, NativeClientConfig>(config);
  rate_tracker_ = std::make_unique<BitgetRateTracker>(mea_, config);

  local_rate_tracker_ = static_cast<BitgetRateTracker*>(rate_tracker_.get());
  start_time_ = GetCurrentTimestamp();
}

BaseRestAuth* BitgetNativePrivateClient::GetAuth() const {
  return auths_.GetRandomTryNotUseFirst();
}

std::shared_ptr<AsioHttpContext> BitgetNativePrivateClient::QueryAccount(const RestParams& params) {
  auto ts = GetCurrentTimestamp();
  UrlParamsBuilder builder;
  builder.PutGet("coin", params.coin());
  auto context = std::shared_ptr<AsioHttpContext>(
      GetAuth()->CreateRequestByGetWithSignature("/api/spot/v1/account/assets", &builder));

  CHECK_API_LIMIT(ActionType::QUERY, QueryType::ACCOUNT);

  if (local_rate_tracker_) {
    local_rate_tracker_->Push(1, ts, ActionType::QUERY, QueryType::ACCOUNT);
  }
  api_req_info_[__func__]++;
  context->query_type = OrderSubTopicId::REST_ACCOUNTS;
  context->extra_info = DebugString();
  return context;
}

std::shared_ptr<AsioHttpContext> BitgetNativePrivateClient::QueryOpenOrders(
    const RestParams& params) {
  auto ts = GetCurrentTimestamp();
  if (!HasEnoughRateLimit(ts, ActionType::QUERY)) {
    LOG(ERROR) << "Hit rate limit. QueryOrders failed";
    return {};
  }

  UrlParamsBuilder builder;
  builder.PutPost("symbol", params.symbol());
  builder.SetIsPost(true);

  CHECK_API_LIMIT(ActionType::QUERY, QueryType::OPEN_ORDER);
  auto context = std::shared_ptr<AsioHttpContext>(
      GetAuth()->CreateRequestByPostWithSignature("/api/spot/v1/trade/open-orders", &builder));

  if (local_rate_tracker_) {
    local_rate_tracker_->Push(1, ts, ActionType::QUERY, QueryType::OPEN_ORDER);
  }

  api_req_info_[__func__]++;

  context->query_type = OrderSubTopicId::REST_OPEN_ORDERS;
  context->extra_info = DebugString();
  return context;
}

std::shared_ptr<AsioHttpContext> BitgetNativePrivateClient::QueryAllOrders(
    const RestParams& params) {
  auto ts = GetCurrentTimestamp();
  UrlParamsBuilder builder;
  builder.PutPost("symbol", params.symbol());
  if (params.has_after()) {
    builder.PutPost("after", params.after());
  }
  if (params.has_before()) {
    builder.PutPost("before", params.before());
  }
  if (params.has_limit()) {
    builder.PutPost("limit", params.limit());
  }
  auto context = std::shared_ptr<AsioHttpContext>(
      GetAuth()->CreateRequestByPostWithSignature("/api/spot/v1/trade/history", &builder));

  CHECK_API_LIMIT(ActionType::QUERY, QueryType::HIST_ORDER);

  if (local_rate_tracker_) {
    local_rate_tracker_->Push(1, ts, ActionType::QUERY, QueryType::HIST_ORDER);
  }
  api_req_info_[__func__]++;

  context->query_type = OrderSubTopicId::REST_ALL_ORDERS;
  context->extra_info = DebugString();
  return context;
}

std::shared_ptr<AsioHttpContext> BitgetNativePrivateClient::QueryFills(const RestParams& params) {
  DLOG_EVERY_N(INFO, 50) << DebugString();
  auto ts = GetCurrentTimestamp();

  UrlParamsBuilder builder;
  builder.PutPost("symbol", params.symbol());
  // according to test, orderId not necessary..
  auto context = std::shared_ptr<AsioHttpContext>(
      GetAuth()->CreateRequestByPostWithSignature("/api/spot/v1/trade/fills", &builder));

  CHECK_API_LIMIT(ActionType::QUERY, QueryType::FILL_ORDER);

  if (local_rate_tracker_) {
    local_rate_tracker_->Push(1, ts, ActionType::QUERY, QueryType::FILL_ORDER);
  }
  api_req_info_[__func__]++;

  context->query_type = OrderSubTopicId::REST_FILL_ORDERS;
  context->extra_info = DebugString();
  return context;
}

std::shared_ptr<AsioHttpContext> BitgetNativePrivateClient::PlaceOrder(const RestParams& params) {
  auto ts = GetCurrentTimestamp();

  UrlParamsBuilder builder;
  builder.PutPost("symbol", params.symbol());
  builder.PutPost("side", params.side());
  builder.PutPost("orderType", params.order_type());
  builder.PutPost("force", params.force());
  builder.PutPost("price", params.price());
  builder.PutPost("quantity", params.quantity());
  builder.PutPost("clientOrderId", params.client_order_id());
  auto context = std::shared_ptr<AsioHttpContext>(
      GetFirstAuth()->CreateRequestByPostWithSignature("/api/spot/v1/trade/orders", &builder));

  CHECK_API_LIMIT(ActionType::PLACE, QueryType::PLACE_ORDER);

  if (local_rate_tracker_) {
    local_rate_tracker_->Push(1, ts, ActionType::PLACE, QueryType::PLACE_ORDER);
  }
  api_req_info_[__func__]++;

  context->query_type = OrderSubTopicId::SUBMIT_RESPONSE;
  context->extra_info = DebugString();
  return context;
}

std::shared_ptr<AsioHttpContext> BitgetNativePrivateClient::CancelOrder(const RestParams& params) {
  auto ts = GetCurrentTimestamp();
  UrlParamsBuilder builder;
  builder.PutPost("symbol", params.symbol());
  builder.PutPost("orderId", params.order_id());
  auto context = std::shared_ptr<AsioHttpContext>(GetFirstAuth()->CreateRequestByPostWithSignature(
      "/api/spot/v1/trade/cancel-order",
      &builder));

  CHECK_API_LIMIT(ActionType::CANCEL, QueryType::CANCEL_ORDER);

  if (local_rate_tracker_) {
    local_rate_tracker_->Push(1, ts, ActionType::CANCEL, QueryType::CANCEL_ORDER);
  }
  api_req_info_[__func__]++;

  context->query_type = OrderSubTopicId::CANCEL_RESPONSE;
  context->extra_info = DebugString();
  return context;
}

std::shared_ptr<AsioHttpContext> BitgetNativePrivateClient::PlaceOrderNorm(
    const OrderExecution& order_exe) {
  const auto& order_spec = *order_exe.order_spec;
  const auto proc_order_id = order_exe.proc_order_id;
  auto params = GetRestOrderParams(order_spec, proc_order_id, 0);
  return PlaceOrder(params);
}

std::shared_ptr<AsioHttpContext> BitgetNativePrivateClient::CancelOrderNorm(
    const OrderExecution& order_exe) {
  auto params = GetRestCancelParams(*order_exe.oc);
  return CancelOrder(params);
}

std::string BitgetNativePrivateClient::DebugString() const {
  double delta_t = (GetCurrentTimestamp() - start_time_) / 1.0e9;

  std::stringstream ss;
  ss << "BitgetNativePrivateClient::DebugString\n";
  ss << "api info\n";
  for (auto& [name, value] : api_req_info_) {
    int32_t blocked = 0;
    if (api_block_info_.count(name) > 0) {
      blocked = api_block_info_.at(name);
    }
    int32_t total_req = value + blocked;
    ss << name << " (total:" << total_req << ", succeeded: " << value << ", blocked: " << blocked
       << ", req_rate: " << value / delta_t << ", block_rate: " << blocked / delta_t << ")\n";
  }
  return ss.str();
}

std::shared_ptr<AsioHttpContext> BitgetNativePrivateClient::SubmitOrderExecution(
    const OrderExecutionProto& order) {
  switch (order.type()) {
    case OrderExecutionProto::SUBMIT_ORDER: {
      auto order_spec = OrderSpec::FromProto(order.order_spec());
      auto params =
          GetRestOrderParams(*order_spec, order.proc_order_id(), order.orig_proc_order_id());
      return PlaceOrder(params);
    }
    case OrderExecutionProto::CANCEL_ORDER: {
      auto order_spec = OrderSpec::FromProto(order.order_spec());
      auto params =
          GetRestOrderParams(*order_spec, order.proc_order_id(), order.orig_proc_order_id());
      return CancelOrder(params);
    }
    default: {
      return nullptr;
    }
  }
}

std::shared_ptr<AsioHttpContext> BitgetNativePrivateClient::SubmitRestQuery(
    const RestQueryProto& query) {
  RestParams params;
  switch (query.type()) {
    case RestQueryProto::QUERY_ACCOUNT_BALANCE: {
      // params.set_coin("USDT");
      return QueryAccount(params);
    }
    case RestQueryProto::QUERY_OPEN_ORDERS: {
      return QueryOpenOrders(params);
    }
    default: {
      return nullptr;
    }
  }
}

}  // namespace coin2::exchange::bitget::api_order
